<script setup lang="ts">
import { ref, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { useValvesStore } from '@/stores/modules/getValvesData';
import { onMounted } from 'vue';
const valvesStore = useValvesStore();
// 页面加载时执行一次获取数据
onMounted(() => {
  valvesStore.getValvesData();
});

const username = ref('');
// 获取屏幕边界到安全区域距离
const safeAreaInsets = ref({ top: 10, left: 0, right: 0, bottom: 0 });

// 模拟从服务器或本地存储获取最新用户信息的异步函数
const fetchLatestUserInfo = async () => {
  try {
    // 模拟网络请求延迟
    await new Promise(resolve => setTimeout(resolve, 500));

    // 模拟从本地存储获取最新用户名
    const latestUsername = uni.getStorageSync('rememberedUsername') || '';

    // 更新用户名状态
    username.value = latestUsername;

    //console.log('Fetched latest user info:', latestUsername);
  } catch (error) {
    console.error('Failed to fetch latest user info:', error);
  }
};

// 页面显示时执行的逻辑
onShow(async () => {
  //console.log('Page shown and logic executed');

  // 强制刷新用户信息
  await fetchLatestUserInfo();

  //如果登录状态失效，则跳转到登录页面
  if ((uni.getStorageSync('rememberedUsername') == '' || null) || (uni.getStorageSync('rememberedPassword') == '' || null)) {
    uni.reLaunch({ url: '/pages/login/login' });
  }


  try {
    const systemInfo = uni.getSystemInfoSync();
    if (systemInfo && systemInfo.safeAreaInsets) {
      safeAreaInsets.value = systemInfo.safeAreaInsets;
    }
  } catch (error) {
    console.error('Failed to get system info:', error);
  }
});

// 计算 navbar 的 paddingTop
const navbarPaddingTop = computed(() => `${safeAreaInsets.value.top + 10}px`);

const reLogin = () => {
  // 清除本地存储的密码和tocken并跳转到登录页面
  //uni.removeStorageSync('rememberedUsername');
  uni.removeStorageSync('rememberedPassword');
  uni.removeStorageSync('tocken')
  uni.navigateTo({ url: '/pages/login/login' });
};
</script>

<template>
  <view class="navbar" :style="{ paddingTop: navbarPaddingTop }">
    <!-- logo文字 -->
    <view class="logo">
      <text style="color: red;font-weight: bold;" v-if="!username">未登录</text>
      <text style="color: white;" v-else>{{ username }}已登录</text>
      <image class="logo-image" src=""></image>
      <!-- <text class="logo-text" @click="reLogin">退出</text> -->
    </view>
  </view>
</template>

<style lang="scss">
/* 自定义导航条 */
.navbar {
  background-image: url(@/static/images/navigator_bg.png);
  background-size: cover;
  position: relative;
  display: flex;
  flex-direction: column;
  padding-bottom: 20px;

  .logo {
    display: flex;
    align-items: center;
    height: 64rpx;
    padding-left: 10rpx;

    .logo-image {
      width: 16rpx;
      height: 39rpx;
    }

    .logo-text {
      flex: 1;
      line-height: 28rpx;
      color: #fff;
      margin: 2rpx 0 0 20rpx;
      padding-left: 20rpx;
      border-left: 1rpx solid #fff;
      font-size: 26rpx;
    }
  }
}
</style>